package com.example.dorm1_demo.config;

import com.example.dorm1_demo.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 获取当前请求的会话对象，若不存在则创建新会话
        HttpSession session = request.getSession();
        // 从会话中获取已登录的用户对象
        User user = (User) session.getAttribute("user");
        
        // 若用户对象为空，表示未登录或登录状态失效
        if (user == null) {
            // 重定向到用户登录页面
            response.sendRedirect("/user/login");
            return false; // 返回false阻止请求继续执行
        }
        
        // 用户已登录，允许请求继续执行
        return true;
    }
}